var Koa = require("koa");
var router = require("koa-router")();
var bodyParser = require("koa-bodyParser");
var nunjucks = require("nunjucks");

var app = new Koa();

// add bodyParser
app.use(bodyParser());


// app.use(async (ctx,next) =>{
//     await next();
//     const rt = ctx.response.get("X-Response-Time");
//     ctx.set("X-Response-Time",`${rt}1111`)
//     console.log(`method:${ctx.method}  url:${ctx.url} -------  rt:${rt} `)
// })

// app.use(async (ctx,next) =>{
//     const start = Date.now();
//     await next();
//     const ms = Date.now() - start;
//     ctx.set("X-Response-Time",`${start}`)
// })

// app.use(async(ctx,next) =>{
//     ctx.body = "Hello World!";
// })

// koa-router
app.use(async(ctx,next) => {
    console.log(`method:${ctx.request.method}  url:${ctx.request.url}`);
    await next();
})

router.get("/hello/:name",async(ctx,next) =>{
    var name = ctx.params.name;
    ctx.response.body = `<h1>hello ${name}</h1>`
})

router.get("/",async(ctx,next) => {
    ctx.response.body = `<form action="/post" method="post">
                            <input type="text" name="name" id="name">
                            <input type="text" name="abc" id="abc">
                            <input type="submit" value="submit">
                        </form>`
})

router.post("/post",async (ctx,next) => {
    var name = ctx.request.body.name | "";
    var abc = ctx.request.body.abc | "";
    console.log(ctx.request.body);
    if(name && abc){
        ctx.response.body = `<h1>name ${name}</h1><h1>abc ${abc}</h1>`
    }else{
        ctx.response.body = `<h1>fail ${abc}</h1>`
    }
})

// add router
app.use(router.routes());

app.listen(3000,()=>{
    console.log("running 3000!");
})

app.listen(3001,()=>{
    console.log("running 3001!");
})


